import { getVideoPreviewUrl } from '@/api/material';
import { downMaterialUrl } from '@/api/newMaterial';
class EncapsulationDownLoad {
	isNetwork = false;
	isAllAbort = false;
	isInterrupt = false;

	currentRequest = 0;
	requestTimeout = 1_000 * 60 * 10;

	constructor(params) {
		const { that, maxRequest = 6 } = params;

		this.direction = that;
		this.maxRequest = maxRequest;
	}

	async startDownloadFile(params) {
		const {
			isNetwork,
			direction,
			isInterrupt,
			maxRequest,
			requestTimeout,
			currentRequest,
			fileSaveSystemAlbum,
			getTemporaryFileDownPath
		} = this;

		if (isInterrupt) {
			return;
		}

		if (!isNetwork && !(await this.getCurrentNetWorkStatus())) {
			formatStorageList.forEach((item) => {
				const { fileTask } = item;

				fileTask && fileTask?.abort();
			});
			return;
		}

		if (currentRequest >= maxRequest) {
			return;
		}

		const formatStorageList = direction.temporaryStorageList.filter((item) => !item.fileTask);

		if (!formatStorageList.length) {
			direction.allFileDownCallBack();
			return;
		}

		formatStorageList.some(async (item) => {
			if (this.currentRequest >= maxRequest) {
				return true;
			}

			++this.currentRequest;

			const url = await getTemporaryFileDownPath(item, params);
			console.log(item);
			const uploadTask = uni.downloadFile({
				url,
				timeout: requestTimeout,
				success: async (res) => {
					const { tempFilePath } = res;

					const status = await fileSaveSystemAlbum({
						tempFilePath,
						type: params === 'new' ? (item.materialType === 1 ? 'image' : 'video') : item.type
					});

					direction.$set(item, 'status', status ? 'success' : 'error');

					!this.isAllAbort && this.startDownloadFile(params);
				},
				fail: (res) => {
					direction.$set(item, 'status', 'error');

					!this.isAllAbort && this.startDownloadFile(params);
				},

				complete: () => {
					--this.currentRequest;
				}
			});

			direction.$set(item, 'fileTask', uploadTask);

			uploadTask.onProgressUpdate(({ progress }) => {
				direction.$set(item, 'status', 'download');
				direction.$set(item, 'progress', progress);
			});
		});
	}

	getTemporaryFileDownPath(params, type) {
		const { id } = params;

		const params2 = {
			resourceId: id,
			preview: false
		};
		const params1 = { materialId: id };
		if (type === 'new') {
			return new Promise((resolve) => {
				downMaterialUrl(type === 'new' ? params1 : params2).then((res) => {
					resolve(res?.data?.url || '');
				});
			});
		} else {
			return new Promise((resolve) => {
				getVideoPreviewUrl(params2).then((res) => {
					resolve(res?.data || '');
				});
			});
		}
	}

	fileSaveSystemAlbum(params) {
		console.log(type);
		const { type, tempFilePath } = params;
		const uniApi = type === 'image' ? uni.saveImageToPhotosAlbum : uni.saveVideoToPhotosAlbum;

		return new Promise((resolve) => {
			/**
			 * saveVideoToPhotosAlbum  保存视频到系统相册。支持mp4视频格式。
			 * saveImageToPhotosAlbum  保存图片到系统相册。
			 */

			uniApi({
				filePath: tempFilePath,
				success: (res) => {
					resolve(res.errMsg);
				},

				fail: (res) => {
					resolve(false);
				}
			});
		});
	}

	getCurrentNetWorkStatus() {
		return new Promise((resolve) => {
			uni.getNetworkType({
				success: (res) => {
					const { networkType } = res;

					if (networkType === 'wifi') {
						resolve(true);
						return;
					}

					uni.showModal({
						title: '提示',
						content: '当前网络处于非Wi-Fi状态，是否继续下载？',
						success: (res) => {
							const { confirm } = res;

							confirm && (this.isNetwork = true);
							resolve(confirm);
						}
					});
				}
			});
		});
	}

	singleAbortUpload(params) {
		const { direction } = this;
		const { index } = params;

		const singleItem = direction.temporaryStorageList[index] || {};

		singleItem.fileTask?.abort();

		direction.$set(singleItem, 'status', 'error');
		direction.$set(singleItem, 'fileTask', undefined);
	}

	allAbortUpload() {
		this.isAllAbort = true;

		const { direction } = this;

		direction.temporaryStorageList.forEach((item) => {
			const { status, fileTask } = item;

			if (status === 'download') {
				fileTask?.abort();
				direction.$set(item, 'status', 'error');
				direction.$set(item, 'fileTask', undefined);
			}
		});
	}
}

export default EncapsulationDownLoad;
